package question

import "strconv"

//43. 字符串相乘
func multiply(num1 string, num2 string) string {
	var l, s string
	if len(num1) > len(num2) {
		l = num1
		s = num2
	} else {
		l = num2
		s = num1
	}
	temp := 0
	arr := make([][]int, 0)
	for i := len(s) - 1; i >= 0; i-- {
		n1, _ := strconv.Atoi(s[i : i+1])
		res := make([]int, len(s)-1-i)
		for j := len(l) - 1; j >= 0; j-- {
			n2, _ := strconv.Atoi(l[j : j+1])
			n := n1*n2 + temp
			temp = n / 10
			res = append(res, n%10)
		}
		if temp > 0 {
			res = append(res, temp)
			temp = 0
		}
		arr = append(arr, res)
	}
	ans := make([]int, 0)
	for _, v := range arr {
		ans = addSlice(ans, v)
	}
	target := ""
	for i := len(ans) - 1; i >= 0; i-- {
		if i == len(ans)-1 && ans[i] == 0 {
			for ans[i] == 0 {
				i--
				if i == -1 {
					return "0"
				}
			}
		}
		target += strconv.Itoa(ans[i])
	}
	return target
}

func addSlice(nums1, nums2 []int) []int {
	res := make([]int, 0)
	i, temp := 0, 0
	for i < len(nums1) && i < len(nums2) {
		sum := nums1[i] + nums2[i] + temp
		temp = sum / 10
		res = append(res, sum%10)
		i++
	}
	if len(nums1) > len(nums2) {
		for i < len(nums1) {
			sum := nums1[i] + temp
			temp = sum / 10
			res = append(res, sum%10)
			i++
		}
	} else {
		for i < len(nums2) {
			sum := nums2[i] + temp
			temp = sum / 10
			res = append(res, sum%10)
			i++
		}
	}
	if temp > 0 {
		res = append(res, temp)
	}
	return res
}
